<?php
class QProductImage
{	
	static $_table = 'product_images';
	
	public function __construct($p_strCountry)
	{
		$this->_country	= $p_strCountry;
		$this->_db		= new Common_Db('wms_'.$this->_country . '_bob');
	}
	
	function __destruct() 
	{
		$this->_db->closeConnection();
	}
	
	public function getImageUrl()
	{		
		$strQuery	=  'SELECT distinct a.sku as sku, f.name as name, f.description as description, "" as brand, b.url_key,fk_catalog_config as catalog ,substring(UNIX_TIMESTAMP(c.updated_at),-4,4) as `timestamp`  from catalog_config a 
						 INNER JOIN catalog_brand b ON a.fk_catalog_brand = b.id_catalog_brand 
						 INNER JOIN catalog_product_image c ON a.id_catalog_config = c.fk_catalog_config
						 INNER JOIN catalog_config f ON a.sku = f.sku
						WHERE a.status = "active" and c.main =1
						Group by a.sku;'; 				
		$arrData = $this->_db->fetchAll($strQuery); 	 
				 
		//Combine become name of image.
		if($arrData)
		{
			$db	= Zend_Registry::get('db');
			self::delete($this->_country);
			foreach ($arrData as $data)
			{
				$imageName =  $data['url_key'] . '-' . $data['timestamp'] .'-'.  $data['timestamp'] . '-'.
					strrev($data['catalog']) .  '-1-product.jpg' ;	
				$p_arrParams =array(
					'sku' => $data['sku'],
					'link_image' => $imageName,
					'name' => $data['name'],
					'description' => $data['description'],
					'brand' => $data['brand']
					);
			
				$resultValue =$db->insert($this->_country ."_". self::$_table , $p_arrParams);
			}
			$db->closeConnection();
		}
	}
	
	static function getBySku($p_sku, $p_strCountry)
	{
		$strQuery	=	'SELECT `sku` , `link_image` FROM `' . $p_strCountry.'_'.self::$_table .'` WHERE `sku`="'.$p_sku . '"';
		$db 		=	Zend_Registry::get('db');
		$arrData 	=	$db->fetchAll($strQuery);
		$db->closeConnection();
		return $arrData;
	}	
	
	public static function insert($p_arrParams, $p_Country)
	{
		$db	= Zend_Registry::get('db');
		$resultValue =$db->insert($p_Country ."_". self::$_table , $p_arrParams);
		$db->closeConnection();
		return $resultValue;
	}
	
	public static function update($p_arrParams, $p_Country)
	{
		$db	= Zend_Registry::get('db');
		$resultValue = $db->update($p_Country ."_". self::$_table, $p_arrParams, "sku=" . "'" .$p_arrParams["sku"] . "'");
		$db->closeConnection();
		return $resultValue;
	}
	
	public static function delete($p_Country)
	{
		$strQuery	=	'TRUNCATE ' . $p_Country.'_'.self::$_table .';';
		$db 		=	Zend_Registry::get('db');
		$arrData 	=	$db->execute($strQuery);
		$db->closeConnection();
	}
}
?>